package com.biubiux2.async;

import com.biubiux2.async.consumer.MsgEventHandler;
import com.biubiux2.async.consumer.entity.MsgEvent;
import com.biubiux2.async.factory.MsgEventFactory;
import com.lmax.disruptor.EventFactory;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.YieldingWaitStrategy;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Lijinbao
 * @since 8/8/2022 1:40 PM
 */
public class DisruptorUtil {

    public static RingBuffer<MsgEvent> ringBuffer;

    public static Disruptor<MsgEvent> disruptor;
    private static ExecutorService executorService;

    private static boolean initiated = false;

    public static void init() {
        executorService = Executors.newCachedThreadPool();
        EventFactory<MsgEvent> msgEventFactory = new MsgEventFactory();

        int ringBufferSize = 1024 * 1024;
        disruptor =
                new Disruptor<>(msgEventFactory, ringBufferSize, executorService, ProducerType.MULTI, new YieldingWaitStrategy());
        disruptor.handleEventsWith(new MsgEventHandler());
        disruptor.start();
        ringBuffer = disruptor.getRingBuffer();
        initiated = true;
    }

    public static void shutDown() {
        if (initiated) {
            executorService.shutdown();
            disruptor.shutdown();
        }
    }
}
